
package io.dbw.modules.business.controller.sys;

import io.dbw.common.annotation.SysLog;
import io.dbw.common.enums.BusinessTypeEnum;
import io.dbw.common.exception.BusinessException;
import io.dbw.common.utils.Constant;
import io.dbw.common.utils.ListUtils;
import io.dbw.common.utils.Result;
import io.dbw.modules.business.entity.SysMenuEntity;
import io.dbw.modules.business.service.ShiroService;
import io.dbw.modules.business.service.SysMenuService;
import io.dbw.modules.business.service.SysUserService;
import io.dbw.modules.business.vo.CommonUserVO;
import io.dbw.modules.business.vo.MenuVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统菜单
 *
 * 
 */
@Validated
@RestController
@ApiIgnore
@RequestMapping("/sys/menu")
@Api(tags = "菜单管理")
public class SysMenuController extends AbstractController {
	@Autowired
	private SysMenuService sysMenuService;
	@Autowired
	private ShiroService shiroService;
	@Autowired
	private SysUserService sysUserService;
	/**
	 * 导航菜单
	 */
	@GetMapping("/nav")
	public Result nav(){
		CommonUserVO user = getUser();
		List<SysMenuEntity> menuList = sysMenuService.getUserMenuList(getUserId());
		Set<String> permissions = shiroService.getUserPermissions(user.getUserId() );
		Map<String,Object> r=new HashMap<String, Object>();
		r.put("menuList", menuList);
		r.put("permissions", permissions);
		return writeSuccess(r);
	}
	
	/**
	 * 所有菜单列表
	 */
	@GetMapping("/list")
	//@RequiresPermissions("business:menu:list")
	public Result list(){
		List<SysMenuEntity> menuList = sysMenuService.list();
		for(SysMenuEntity sysMenuEntity : menuList){
			SysMenuEntity parentMenuEntity = sysMenuService.getById(sysMenuEntity.getParentId());
			if(parentMenuEntity != null){
				sysMenuEntity.setParentName(parentMenuEntity.getName());
			}
		}
		List<SysMenuEntity> list= menuList.stream().sorted(
                Comparator.comparing(SysMenuEntity::getOrderNum)
        ).collect(Collectors.toList());
		return writeSuccess(list);
	}
	
	/**
	 * 选择菜单(添加、修改菜单)
	 */
	@GetMapping("/getUserMenuTree")
	//@RequiresPermissions("business:menu:select")
	@ApiOperation(value="获取用户菜单")
	public Result<List<MenuVO>> getUserMenuTree(){
		CommonUserVO user = getUser();
		List<SysMenuEntity> menuList =sysUserService.queryAllPermsByUserId(user.getUserId() );
		List<MenuVO> list = ListUtils.getMenuList(ListUtils.removeDuplicateDept(menuList),1);
		return writeSuccess(list);
	}
	
	/**
	 * 菜单信息
	 */
	@GetMapping("/info/{menuId}")
	//@RequiresPermissions("business:menu:info")
	public Result info(@PathVariable("menuId") Long menuId){
		SysMenuEntity menu = sysMenuService.getById(menuId);
		return writeSuccess(menu);
	}
	
	/**
	 * 保存
	 */
	@SysLog(value = "保存菜单",businessType = BusinessTypeEnum.INSERT)
	@PostMapping("/save")
	//@RequiresPermissions("business:menu:save")
	public Result save(@RequestBody SysMenuEntity menu){
		//数据校验
		verifyForm(menu);
		
		sysMenuService.save(menu);
		
		return writeSuccess();
	}
	
	/**
	 * 修改
	 */
	@SysLog(value = "修改菜单",businessType = BusinessTypeEnum.UPDATE)
	@PostMapping("/update")
	//@RequiresPermissions("business:menu:update")
	public Result update(@RequestBody SysMenuEntity menu){
		//数据校验
		verifyForm(menu);
				
		sysMenuService.updateById(menu);
		
		return writeSuccess();
	}
	
	/**
	 * 删除
	 */
	@SysLog(value = "删除菜单",businessType = BusinessTypeEnum.DELETE)
	@PostMapping("/delete/{menuId}")
	//@RequiresPermissions("business:menu:delete")
	public Result delete(@PathVariable("menuId") long menuId){
		if(menuId <= 31){
			return writeFail("系统菜单，不能删除");
		}

		//判断是否有子菜单或按钮
		List<SysMenuEntity> menuList = sysMenuService.queryListParentId(menuId);
		if(menuList.size() > 0){
			return writeFail("请先删除子菜单或按钮");
		}

		sysMenuService.delete(menuId);

		return writeSuccess();
	}
	
	/**
	 * 验证参数是否正确
	 */
	private void verifyForm(SysMenuEntity menu){
		if(StringUtils.isBlank(menu.getName())){
			throw new BusinessException("菜单名称不能为空");
		}
		
		if(menu.getParentId() == null){
			throw new BusinessException("上级菜单不能为空");
		}
		
		//菜单
		if(menu.getType() == Constant.MenuType.MENU.getValue()){
			if(StringUtils.isBlank(menu.getUrl())){
				throw new BusinessException("菜单URL不能为空");
			}
		}
		
		//上级菜单类型
		int parentType = Constant.MenuType.CATALOG.getValue();
		if(menu.getParentId() != 0){
			SysMenuEntity parentMenu = sysMenuService.getById(menu.getParentId());
			parentType = parentMenu.getType();
		}
		
		//目录、菜单
		if(menu.getType() == Constant.MenuType.CATALOG.getValue() ||
				menu.getType() == Constant.MenuType.MENU.getValue()){
			if(parentType != Constant.MenuType.CATALOG.getValue()){
				throw new BusinessException("上级菜单只能为目录类型");
			}
			return ;
		}
		
		//按钮
		if(menu.getType() == Constant.MenuType.BUTTON.getValue()){
			if(parentType != Constant.MenuType.MENU.getValue()){
				throw new BusinessException("上级菜单只能为菜单类型");
			}
			return ;
		}
	}
}
